﻿namespace _2_NovaAdmin.Application.Services.User;

//[Authorize]
[ResponseCache(Duration = 10, Location = ResponseCacheLocation.Client)]
public class UserService : IDynamicController, IScopedDependency
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IRepository<_3_NovaAdmin.Domain.Entities.User> _userRepository;
    private readonly IMediator _mediator;
    private readonly IMapper _mapper;
    private readonly StackExchange.Redis.IDatabase _redisDb;
    private readonly MigrationHandler _migration;
    public UserService(IRepository<_3_NovaAdmin.Domain.Entities.User> userRepository, IMediator mediator, IUnitOfWork unitOfWork, RedisClient client, MigrationHandler migration, IMapper mapper)
    {
        _userRepository = userRepository;
        _unitOfWork = unitOfWork;
        _mediator = mediator;
        _redisDb = client.GetDatabase();
        _migration = migration;
        _mapper = mapper;
    }
    public async Task<IActionResult> AddUser([FromBody] DtoUserRequest request)
    {
        var r = _mapper.Map<DtoUserRequest, _3_NovaAdmin.Domain.Entities.User>(request);
        _migration.GenerateEntitiesFromDb();
        //await _userRepository.InsertSingleData(new _3_NovaAdmin.Domain.Entities.User("王琪"));
        await _mediator.Send(new CreateUserCommand(""));
        return new JsonResult(new { });
    }

    public async Task<IActionResult> AddUser1([FromBody] DtoUserRequest request)
    {
        await _mediator.Send(new CreateUserCommand(""));
        //return new ApiResult { };
        //// 非泛型成功
        //var result = ApiResult.Ok();

        //// 非泛型失败
        //var error = ApiResult.Fail(400, "参数错误");

        //// 泛型成功
        //var dataResult = ApiResult<string>.Ok("Hello World");

        //// 泛型失败
        //var dataError = ApiResult<int>.Fail(404, "未找到数据");
        return new JsonResult(ApiResult<object>.Ok(new { id = Guid.NewGuid() }));
    }

    public async Task Test()
    {
        await _redisDb.StringSetAsync("111", "222");
    }

    public async Task<IActionResult> Test1()
    {
        var result = await _redisDb.StringGetAsync("111");
        return new JsonResult(result);
    }

    public async Task<IActionResult> Test2()
    {
        await Task.Delay(2000);
        return new JsonResult(new { Guid = Guid.NewGuid() });
    }

    //[HttpGet("{id}")]
    [ResponseCache(
    Duration = 10,
    Location = ResponseCacheLocation.Any,
    VaryByQueryKeys = new[] { "id" },
    NoStore = false)]
    public IActionResult GetById(int id)
    {
        return new JsonResult(new { Guid = Guid.NewGuid() });
    }

    [ApiExplorerSettings(IgnoreApi = true)]
    public async Task<_3_NovaAdmin.Domain.Entities.User> ValidateUser(DtoLoginRequest request)
    {
        var result = await _userRepository.FirstOrDefaultAsync(m => true);
        return result;
    }
}
